<?php
class FavorController extends CController{
	public function actionDelete(){
		$tagName = trim(urldecode(NC::_p('tag','')));
		//取出tag
		$favor = Favor::model()->findByAttributes(array('favor_name'=>$tagName));
		if(!$favor)NC::json(false,'已删除，请重新刷新页面！');
		//解码
		$userIDs = json_decode($favor->user_ids,true);
		$userIDs['uids'] = array_diff($userIDs['uids'],array(Yii::app()->user->id));//删掉我的ID
		if(empty($userIDs['uids'])){//为空，则在favor表中删除这条记录
			if(!Favor::model()->deleteByPk($favor->favor_id))
				NC::json(false,'删除失败，请重试！');
		}else{//更新
			--$userIDs['count'];//统计数据减一
			$favor->user_ids = json_encode($userIDs);
			--$favor->user_count;
			$favor->favor_time = time();
			if(!$favor->save());
				NC::json(false,'删除失败，请重试！');
		}
		$user = User::model()->findByPk(Yii::app()->user->id);
		$newUserFavor = trim(str_replace($tagName,'',$user->favor_name));
		if(!User::model()->updateByPk(Yii::app()->user->id,array('favor_name'=>$newUserFavor)))
			NC::json(false,'已删除!');
		NC::json(true);
	}
	public function actionAdd(){
		$tagName = trim(urldecode(NC::_p('tag','')));
		//验证是否有这个tag
		$favorAR = new Favor;
		$favor = $favorAR->findByAttributes(array('favor_name'=>$tagName));
		if(!$favor){//数据库不存在，这是一个新的TAG
			$favorName = array('uids'=>array(Yii::app()->user->id),'count'=>1);
			$favorAR->favor_name = $tagName;
			$favorAR->user_ids = json_encode($favorName);
			$favorAR->user_count = 1;
			$favorAR->favor_time = time();
			if(!$favorAR->save())
				NC::json(false,'很抱歉，添加失败，请您重试！');
			else
				$primaryKey = $favorAR->primaryKey;

		}else{
			$userIDs = json_decode($favor->user_ids,true);
			++$userIDs['count'];
			if(in_array(Yii::app()->user->id,$userIDs['uids']))
				NC::json(false,'已添加过，请不要重复添加！');
			array_push($userIDs['uids'],Yii::app()->user->id);
			$favor->user_ids = json_encode($userIDs);
			++$favor->user_count;
			$favor->favor_time = time();
			if(!$favor->save())
				NC::json(false,'很抱歉，添加失败，请您重试！');
			else
				$primaryKey = $favor->primaryKey;
		}
		//取出用户表信息，并更新
		$user = User::model()->findByPk(Yii::app()->user->id);
		$userFavorName = trim($user->favor_name . " ".$tagName);
		//NC::json(false,$user->favor_name);
		if(!User::model()->updateByPk(Yii::app()->user->id,array('favor_name'=>$userFavorName)))
			NC::json(false,$user->getErrors());
		NC::json(true,$primaryKey);
	}
}